<?php
declare (strict_types = 1);

namespace app\common\model;

use think\Model;
use think\response\Json;

/**
 * @mixin \think\Model
 */
class ProCate extends Base
{

    protected $name = 'pro_cate';

    public static function _save($param, $admin = '')
    {
        parent::startTrans();
        try {
            if (isset($param['id']) && $param['id']) {
                $find=parent::where(array('id'=>$param['id'],'is_del'=>0))->find();
                $score=parent::where(['pro_id'=>$find['pro_id'],'is_del'=>0])->where('id','<>',$param['id'])->sum('score');
                $num=Pro::where(array('id'=>$find['pro_id'],'is_del'=>0))->value('num');
                $scores=$score+$param['score'];

                /*if($scores>$num){
                    return ['code'=>-1,'msg'=>'总分数不得超过'.$num.'分'];
                }*/
                parent::update($param);
            } else {
                $score=parent::where(array('pro_id'=>$param['pro_id'],'is_del'=>0))->sum('score');
                $num=Pro::where(array('id'=>$param['pro_id'],'is_del'=>0))->value('num');
                $scores=$score+$param['score'];
               /* if($scores>$num){
                    return ['code'=>-1,'msg'=>'总分数不得超过'.$num.'分'];
                }*/
                parent::create($param);
            }
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功'];

        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function getCate($id = 0)
    {
        if($id==0){
            return Pro::where(['is_del' => 0])->order('sort asc')->field('id,title')->select();
        }else{
            return parent::where(['pro_id' => $id, 'is_del' => 0])->order('sort asc')->field('id,title')->select();  
        }
    }

}
